/**
 * Created by meiyun1 on 2017/8/6.
 */
import _ from 'lodash'
import parseFile from 'parse-filepath'

/**
 * 获取router中的顶层节点
 * @param routers
 * @param routerName
 * @returns {*}
 */
export function getTopRouter (routers, routerName) {
  if (!routers || routers.length === 0) {
    return false
  }
  let router
  router = _.find(routers, obj => {
    return obj.name === routerName
  })
  if (router) {
    return router
  } else {
    router = _.find(routers, obj => {
      return getTopRouter(obj.children, routerName)
    })
  }
  if (!router) {
    return false
  }
  return router
}
/**
 * 获取router的父亲节点
 * @param routers
 * @param routerName
 * @param parent
 * @returns {boolean}
 */
export function getRouterParent (routers, routerName, parent) {
  if (!routers || routers.length === 0) {
    return false
  }
  let router = false
  routers.every(obj => {
    if (obj.name === routerName) {
      router = obj
      router.parent = parent
      return false
    }
    router = getRouterParent(obj.children, routerName, obj)
    if (router) {
      return false
    }
    return true
  })
  return router
}

/**
 * 去掉对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function clearEmptyValue (obj) {
  Object.keys(obj).forEach(key => {
    if (!obj[key] && obj[key] !== 0) {
      delete obj[key]
    }
  })
  return obj
}

export function getSortAndOrder (obj) {
  if (obj.prop) {
    let data = {
      order: obj.prop
    }
    switch (obj.order) {
      case 'ascending':
        data['sort'] = 'asc'
        break
      case 'descending':
        data['sort'] = 'desc'
        break
    }
    return data
  }
  return false
}

export function parseFilePath (filePath) {
  return parseFile(filePath)
}
